//
//  StylistDetailViewController.m
//  MyDIYHouse
//
//  Created by dlios on 15-7-1.
//  Copyright (c) 2015年 李平洋. All rights reserved.
//

#import "StylistDetailViewController.h"
#import "StylistModel.h"
#import "HTTPTool.h"
#import "CaseCell.h"
#import "CaseModel.h"
#import "NewCaseDetailViewController.h"
#import "MatchTableViewCell.h"
#import "MatchModel.h"
#import "MJRefresh.h"
#import "UIImageView+WebCache.h"
#import "UIButton+WebCache.h"
#import "StrategyModel.h"
#import "StylistDetailIdeabookCollectionViewCell.h"
#import "StrategyDetailViewController.h"
#import "MatchDetailViewController.h"

#define kHeight [UIScreen mainScreen].bounds.size.height
#define kWidth [UIScreen mainScreen].bounds.size.width

@interface StylistDetailViewController ()<UICollectionViewDataSource,UICollectionViewDelegate,UITableViewDataSource,UITableViewDelegate>

@property (nonatomic,retain)StylistModel *stylist;

@property (nonatomic,retain)UIScrollView *backScrollView;

//上面部分
@property (nonatomic,retain)UIImageView *informationImageView;


@property (nonatomic,retain)UIButton *backButton;
@property (nonatomic,retain)UIButton *phoneButton;
@property (nonatomic,retain)UILabel *titleLabel;
@property (nonatomic,retain)UIImageView *userImageView;
@property (nonatomic,retain)UILabel *numberLabel;


@property (nonatomic,retain)UISegmentedControl *seg;





//下面部分
@property (nonatomic,retain)UITableView *projectTableView;
@property (nonatomic,retain)UITableView *photoTableView;

@property (nonatomic,retain)UICollectionView *ideabookCollectionView;




//几个参数写成属性
@property (nonatomic,copy)NSString *start;
@property (nonatomic,copy)NSString *count;
@property (nonatomic,copy)NSString *user;


//案例接口的额外参数
@property (nonatomic,assign)NSInteger projectstart;
@property (nonatomic,copy)NSString *projectcount;

//照片接口的额外参数
@property (nonatomic,assign)NSInteger matchstart;
@property (nonatomic,copy)NSString *matchcount;

@property (nonatomic,retain)NSMutableArray *strategyArr;
@property (nonatomic,retain)NSMutableArray *projectArr;
@property (nonatomic,retain)NSMutableArray *matchArr;
@end

@implementation StylistDetailViewController
- (void)dealloc
{
    [self.myUserName release];
    self.backScrollView.delegate = nil;
    self.ideabookCollectionView.delegate = nil;
    self.projectTableView.delegate = nil;
    self.photoTableView.delegate = nil;
    [super dealloc];
}


- (instancetype)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.strategyArr = [NSMutableArray array];
        self.projectArr = [NSMutableArray array];
        self.matchArr = [NSMutableArray array];
        self.start = @"0";
        self.count = @"10";
        self.user = @"(null)";
        
        self.projectstart = 0;
        self.projectcount = @"5";
        
        self.matchstart = 0;
        self.matchcount = @"5";
        
    }
    return self;
}

- (void)createData
{
#pragma mark //设计师资料相关接口
    NSString *urlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/summary?username=%@&user=null&",self.myUserName,self.myUserName];
    
    [HTTPTool get:urlStr body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        self.stylist = [[StylistModel alloc] initWithDic:dic];
        [self.informationImageView sd_setImageWithURL:[NSURL URLWithString:[self.stylist.userImage objectForKey:@"large"]]];
        self.titleLabel.text = self.stylist.userName;
        [self.userImageView sd_setImageWithURL:[NSURL URLWithString:[self.stylist.userImage objectForKey:@"large"]]];
        
        NSString *numberStr = [NSString stringWithFormat:@"关注  %@     粉丝  %@",[self.stylist.followingNum stringValue],[self.stylist.followerNum stringValue]];
        self.numberLabel.text = numberStr;
        
        NSString *projectNumStr = [NSString stringWithFormat:@"案例:%@",[self.stylist.projectNum stringValue]];
        NSString *ideabookNumStr = [NSString stringWithFormat:@"灵感集:%@",[self.stylist.ideabookNum stringValue]];
        NSString *photoNumStr = [NSString stringWithFormat:@"分享:%@",[self.stylist.photoNum stringValue]];
        
        
        self.seg = [[UISegmentedControl alloc] initWithItems:@[projectNumStr,ideabookNumStr,photoNumStr]];
        self.seg.frame = CGRectMake(0, 220, kWidth, 50);
        [self.backScrollView addSubview:self.seg];
        [self.seg release];
        self.seg.backgroundColor = [UIColor whiteColor];
        self.seg.tintColor = [UIColor colorWithRed:23 / 255.0 green:176 / 255.0 blue:138 / 255.0 alpha:1];
        
        //为这个SC写点击方法
        [_seg addTarget:self action:@selector(click:) forControlEvents:UIControlEventValueChanged];
        
        //选中index= 2//修改默认的被选中的方块
        //  _seg.selectedSegmentIndex = 2;
        
        
    } failure:^(NSError *error) {
        
    }];
    
    //灵感集相关接口
    
    NSString *ideabookUrlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/ideabooks?start=%@&count=%@&user=%@",self.myUserName,self.start,self.count,self.user];
    
    [HTTPTool get:ideabookUrlStr body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        NSArray *ideabooksArr = dic[@"ideabooks"];
        for (NSDictionary *tempDic in ideabooksArr) {
            StrategyModel *strategy = [[StrategyModel alloc] initWithDic:tempDic];
            // NSLog(@"%@",strategy.title);
            [self.strategyArr addObject:strategy];
            [strategy release];
        }
        
        
        [self.ideabookCollectionView reloadData];
        
    } failure:^(NSError *error) {
        
    }];
    
    //案例相关接口
    NSString *projectUrlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/projects?start=%ld&count=%@&user=%@",self.myUserName,self.projectstart,self.projectcount,self.user];
    
    
    
    [HTTPTool get:projectUrlStr body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        NSArray *projectsArr = dic[@"projects"];
        for (NSDictionary *tempDic in projectsArr) {
            CaseModel *caseM = [[CaseModel alloc] initWithDic:tempDic];
            // NSLog(@"%@",caseM.title);
            
            [self.projectArr addObject:caseM];
            
        }
        
        [self.projectTableView reloadData];
        [self.projectTableView footerEndRefreshing];
        
        
    } failure:^(NSError *error) {
        
    }];
    
    
}

- (void)createMatchData
{
    
    //照片相关接口
    NSString *matchUrlStr = [NSString stringWithFormat:@"http://api.guju.com.cn/v2/user/%@/photos?start=%ld&count=%@&user=%@ ",self.myUserName,self.matchstart,self.matchcount,self.user];
    
    
    
    [HTTPTool get:matchUrlStr body:nil httpResult:JSON success:^(id result) {
        NSDictionary *dic = result;
        NSArray *photoArr = dic[@"photos"];
        for (NSDictionary *tempDic in photoArr) {
            MatchModel *match = [[MatchModel alloc] initWithDic:tempDic];
            // NSLog(@"%@",caseM.title);
            
            [self.matchArr addObject:match];
            
        }
        
        [self.photoTableView reloadData];
        [self.photoTableView footerEndRefreshing];
        
        
    } failure:^(NSError *error) {
        
    }];
    
    
    
}

- (void)viewWillAppear:(BOOL)animated
{
    self.tabBarController.tabBar.hidden = YES;
    self.navigationController.navigationBar.hidden = YES;
    [self createData];
    [self createMatchData];
    
}


- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    
    
    
    
    
    self.backScrollView = [[UIScrollView alloc] initWithFrame:CGRectMake(0, 0, kWidth, kHeight)];
    [self.view addSubview: self.backScrollView];
    //self.backScrollView.backgroundColor = [UIColor cyanColor];
    self.backScrollView.bounces = NO;
    self.backScrollView.delegate = self;
    // self.backScrollView.userInteractionEnabled = YES;
#pragma mark 上面部分
    
    //self.informationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -150, kWidth, 360)];
    self.informationImageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, -20, kWidth, 240)];
    // self.informationImageView.backgroundColor = [UIColor yellowColor];
    [self.backScrollView addSubview:self.informationImageView];
    
    //毛玻璃效果
    //创建一个毛玻璃效果
    UIBlurEffect *blur = [UIBlurEffect effectWithStyle:UIBlurEffectStyleLight];
    //创建一个用来显示模糊效果的view
    UIVisualEffectView *maoboliview = [[UIVisualEffectView alloc] initWithEffect:blur];
    
    maoboliview.frame =CGRectMake(0, 0, kWidth, 240);
    [self.informationImageView addSubview:maoboliview];
    
    
    //图片保持原有比例
    //self.informationImageView.contentMode = UIViewContentModeScaleAspectFill;
    
    self.backScrollView.contentSize = CGSizeMake(0, 897-76);
    
    
    
    //返回按钮
    self.backButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.backButton.frame = CGRectMake(20, 20, 44, 44);
    [self.backButton setBackgroundImage:[UIImage imageNamed:@"iconfont-fanhui"] forState:0];
    [self.view addSubview:self.backButton];
    [self.backButton addTarget:self action:@selector(backbtnclick:) forControlEvents:UIControlEventTouchUpInside];
    
    //打电话按钮
    self.phoneButton = [UIButton buttonWithType:UIButtonTypeCustom];
    self.phoneButton.frame = CGRectMake(kWidth-64, 20, 44, 44);
    [self.phoneButton setBackgroundImage:[UIImage imageNamed:@"iconfont-dadianhua"] forState:0];
    [self.view addSubview:self.phoneButton];
    [self.phoneButton addTarget:self action:@selector(phonebtnclick:) forControlEvents:UIControlEventTouchUpInside];
    
    //titleLabel
    self.titleLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth/2 -50, 20, 100, 44)];
    [self.view addSubview:self.titleLabel];
    self.titleLabel.textColor = [UIColor whiteColor];
    self.titleLabel.textAlignment = 1;
    self.titleLabel.hidden = YES;
    
    //用户头像
    self.userImageView = [[UIImageView alloc] initWithFrame:CGRectMake(kWidth/2-50, 64, 100, 100)];
    [self.informationImageView addSubview:self.userImageView];
    self.userImageView.layer.cornerRadius = 50;
    self.userImageView.layer.masksToBounds = YES;
    [self.userImageView release];
    
    //关注粉丝数量Label
    self.numberLabel = [[UILabel alloc] initWithFrame:CGRectMake(kWidth/2-100, 184, 200, 40)];
    [self.informationImageView addSubview:self.numberLabel];
    self.numberLabel.textAlignment = 1;
    //    self.numberLabel.backgroundColor = [UIColor greenColor];
    [self.numberLabel release];
    
    
    
    
    
#pragma mark 下面部分
    
    self.photoTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 270, kWidth, 551)];
    [self.backScrollView addSubview:self.photoTableView];
    self.photoTableView.delegate = self;
    self.photoTableView.dataSource = self;
    
    self.photoTableView.scrollEnabled = NO;
    self.photoTableView.rowHeight = 250;
    [self.photoTableView addFooterWithCallback:^{
        self.matchstart = self.matchstart+5;
        [self createMatchData];
    }];
    
    UICollectionViewFlowLayout *flowLayout = [[UICollectionViewFlowLayout alloc] init];
    flowLayout.itemSize = CGSizeMake(kWidth/2, kWidth/4*3);
    flowLayout.minimumLineSpacing = 0;
    flowLayout.minimumInteritemSpacing = 0;
    flowLayout.sectionInset = UIEdgeInsetsMake(0, 0, 0, 0);
    
    self.ideabookCollectionView = [[UICollectionView alloc] initWithFrame:CGRectMake(0, 270, kWidth, 551) collectionViewLayout:flowLayout];
    self.ideabookCollectionView.backgroundColor = [UIColor whiteColor];
    [self.backScrollView addSubview:self.ideabookCollectionView];
    self.ideabookCollectionView .dataSource = self;
    self.ideabookCollectionView .delegate =self;
    self.ideabookCollectionView.scrollEnabled = NO;
    
    // 注册
    // 第一个参数:需要制定注册的类型
    // 第二个参数:重用标志
    [self.ideabookCollectionView  registerClass:[StylistDetailIdeabookCollectionViewCell class] forCellWithReuseIdentifier:@"ideaboocollreuse"];
    
    
    self.projectTableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 270, kWidth, 551)];
    [self.backScrollView addSubview:self.projectTableView];
    self.projectTableView.delegate = self;
    self.projectTableView.dataSource = self;
    self.projectTableView.rowHeight=210;
    self.projectTableView.scrollEnabled = NO;
    
    [self.projectTableView addFooterWithCallback:^{
        self.projectstart = self.projectstart+5;
        [self createData];
    }];
    // self.projectTableView.backgroundColor = [UIColor greenColor];
    
    
    
    
    
}


#pragma mark scrollView代理的方法



- (void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if(scrollView == self.backScrollView)
    {
        if (scrollView.contentOffset.y > 240-84-5) {
            // NSLog(@"aaa");
            self.titleLabel.hidden = NO;
            self.ideabookCollectionView.scrollEnabled = YES;
            self.projectTableView.scrollEnabled = YES;
            self.photoTableView.scrollEnabled = YES;
            self.numberLabel.hidden = YES;
        }else
        {
            self.titleLabel.hidden = YES;
            self.ideabookCollectionView.scrollEnabled = NO;
            self.projectTableView.scrollEnabled = NO;
            self.photoTableView.scrollEnabled = NO;
            self.numberLabel.hidden = NO;
        }
    }
    
}

#pragma mark 案例和图片tableView协议的两个方法
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (tableView == self.projectTableView) {
        return self.projectArr.count;
    }else
        
        return self.matchArr.count;
}

-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if(tableView == self.projectTableView)
    {
        static NSString *reuse=@"reuse";
        CaseCell *cell=[tableView dequeueReusableCellWithIdentifier:reuse];
        if (!cell) {
            cell=[[[CaseCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse] autorelease];
            
        }
        CaseModel *caseClass = self.projectArr[indexPath.row];
        NSDictionary *tempDic=[caseClass.photos firstObject];
        //    NSString *titleStr=[tempDic objectForKey:@"title"];
        NSNumber *picId=[tempDic objectForKey:@"id"];
        NSNumber *picWidth=[tempDic objectForKey:@"width"];
        NSNumber *picHeight=[tempDic objectForKey:@"height"];
        NSString *picUrl=[NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w%@_h%@_m0.jpg",picId,picWidth,picHeight];
        
        //图片
        [cell.furnitureImage sd_setImageWithURL:[NSURL URLWithString:picUrl]];
        //日期
        cell.dateLable.text =caseClass.date;
        cell.likeNumLable.text = [caseClass.likeNum stringValue];
        cell.commentNumLable.text = [caseClass.commentNum stringValue];
        [cell.peopleImageButton sd_setBackgroundImageWithURL:[NSURL URLWithString:[caseClass.user objectForKey:@"userImage"][@"large"]] forState:UIControlStateNormal];
        cell.titleLable.text=caseClass.title;
        // cell.titleLable.text = @"aaa";
        
        return cell;
    }
    else{
        static NSString *reuse3 = @"reuse3";
        MatchTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuse3];
        if (!cell) {
            cell = [[[MatchTableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:reuse3] autorelease];
        }
        //房屋大图片
        MatchModel *match = self.matchArr[indexPath.row];
        NSString *picUrlStr = [NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w%@_h%@_m0.jpg",match.bId, match.width, match.height];
        //NSLog(@"%@",picUrlStr);
        [cell.homeImageView sd_setImageWithURL:[NSURL URLWithString:picUrlStr]];
        
        //设计师头像
        NSDictionary *userDic = match.user;
        NSDictionary *userImage = [userDic objectForKey:@"userImage"];
        
        [cell.headButton sd_setBackgroundImageWithURL:[NSURL URLWithString:[userImage objectForKey:@"large"]] forState:UIControlStateNormal];
        
        // NSLog(@"%@",[match.userImage objectForKey:@"large"]);
        
        
        //设计师名称
        cell.stylistName.text = [userDic objectForKey:@"userName"];
        
        //收藏数量
        cell.starNumber.text = [match.ideabookNum stringValue];
        
        return cell;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (tableView == self.projectTableView) {
        
        
        NewCaseDetailViewController *caseDetailVC = [[NewCaseDetailViewController alloc] init];
        caseDetailVC.myCase = self.projectArr[indexPath.row];
        
        [self.navigationController pushViewController:caseDetailVC animated:YES];
        [caseDetailVC release];
    }
    if (tableView == self.photoTableView) {
        MatchDetailViewController *matchDetailVC = [[MatchDetailViewController alloc] init];
        matchDetailVC.matchModel = self.matchArr[indexPath.row];
        
        NSDictionary *userDic = matchDetailVC.matchModel.user;
        NSDictionary *userImage = [userDic objectForKey:@"userImage"];
        matchDetailVC.matchModel.userImage = userImage;
        matchDetailVC.matchModel.userName = [userDic objectForKey:@"userName"];
        
        [self.navigationController pushViewController:matchDetailVC animated:YES];
        [matchDetailVC release];
    }
        
        
        
}





#pragma mark 灵感集collectionView协议的两个方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.strategyArr.count;
}



- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
    StylistDetailIdeabookCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"ideaboocollreuse" forIndexPath:indexPath];
    //使用了注册,就不需要判断是否为空,因为肯定不为空
    
    // NSDictionary *photoDic =  self.myStrategy.photos[indexPath.row];
    StrategyModel *strategy = self.strategyArr[indexPath.row];
    
    cell.titleLabel.text = strategy.title;
    
    NSArray *photoArr = strategy.photos;
    
    NSString *numStr = [NSString stringWithFormat:@"%ld个收集 . %@个人喜欢",photoArr.count,[strategy.bookmarkNum stringValue]];
    
    cell.numberLabel.text = numStr;
    
    NSDictionary *photoDic = [photoArr firstObject];
    
    NSString *picUrl = [NSString stringWithFormat:@"http://gooju.cn/dimages/%@_0_w%@_h%@_m0.jpg",[photoDic objectForKey:@"id"],[photoDic objectForKey:@"width"],[photoDic objectForKey:@"height"]];
    
    [cell.myImageView sd_setImageWithURL:[NSURL URLWithString:picUrl]];
    
    return cell;
    
}


- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    StrategyDetailViewController *strategyDetailVC = [[StrategyDetailViewController alloc] init];
    strategyDetailVC.myStrategy = self.strategyArr[indexPath.row];
    
    [self.navigationController pushViewController:strategyDetailVC animated:YES];
    
    
    [strategyDetailVC release];
}


//click:点击方法的实现
- (void)click:(UISegmentedControl *)seg
{
    
    if (seg.selectedSegmentIndex == 0) {
        self.photoTableView.hidden = YES;
        self.ideabookCollectionView.hidden = YES;
        self.projectTableView.hidden = NO;
    }
    
    else if (seg.selectedSegmentIndex==1)
    {
        self.photoTableView.hidden = YES;
        self.ideabookCollectionView.hidden = NO;
        self.projectTableView.hidden = YES;
        
    }
    else if(seg.selectedSegmentIndex==2)
    {
        self.photoTableView.hidden = NO;
        self.ideabookCollectionView.hidden = YES;
        self.projectTableView.hidden = YES;
    }
}

- (void)backbtnclick:(UIButton *)button
{
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)phonebtnclick:(UIButton *)button
{
    NSLog(@"%@",self.stylist.phone);
    
    NSString *allString = [NSString stringWithFormat:@"tel:%@",self.stylist.phone];
    
    [[UIApplication sharedApplication] openURL:[NSURL URLWithString:allString]];
}

- (void)viewWillDisappear:(BOOL)animated
{
    self.navigationController.navigationBar.hidden = NO;
    self.tabBarController.tabBar.hidden = NO;
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
 #pragma mark - Navigation
 
 // In a storyboard-based application, you will often want to do a little preparation before navigation
 - (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
 // Get the new view controller using [segue destinationViewController].
 // Pass the selected object to the new view controller.
 }
 */

@end
